package com.bc.wallpaper;

import com.bc.R;
import com.bc.utils.SettingPrefs;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.util.Log;

public class BtcWallPaperSettings extends PreferenceActivity 
	implements SharedPreferences.OnSharedPreferenceChangeListener{
	public static final String SHARED_PREFS_NAME = "btc_wallpaper_prefs";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setPreferenceScreen(createPreferenceHierarchy());
		getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}
	
	private PreferenceScreen createPreferenceHierarchy() { 
		PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
		PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
        dialogBasedPrefCat.setTitle(R.string.livewallpaper_setting_title);
        root.addPreference(dialogBasedPrefCat);

		 // List preference
	    ListPreference listPref = new ListPreference(this);
	    listPref.setEntries(R.array.refresh_time_array);
	    listPref.setEntryValues(R.array.refresh_time_value_str_array);
	    listPref.setDialogTitle(R.string.refresh_setting);
	    listPref.setKey("refresh_list");
	    listPref.setTitle(R.string.refresh_setting);
	    String[] entries = getResources().getStringArray(R.array.refresh_time_array);
	    int position = SettingPrefs.getInstance(this).getIntFromPrefs(SettingPrefs.REFRESH_TIME_POSITION, 0);
	    
	    listPref.setSummary(getString(R.string.refresh_time_txt, entries[position]));
	    dialogBasedPrefCat.addPreference(listPref);
	    
	    return root;
	}
	
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Log.d(getClass().getSimpleName(), "onSharedPreferenceChanged....");
		if (key.equals("refresh_list")) {
			String valueStr = sharedPreferences.getString("refresh_list", "10");
			int value = Integer.parseInt(valueStr);
			Log.d(getClass().getSimpleName(), "pref_value: " + value);
			ListPreference lp = (ListPreference)getPreferenceScreen().findPreference("refresh_list");
			CharSequence[] entries = lp.getEntries();
			int index =  lp.findIndexOfValue((String)valueStr);
			getPreferenceManager().findPreference("refresh_list").setSummary(getString(R.string.refresh_time_txt, entries[index]));
			SettingPrefs.getInstance(this).putIntToPrefs(SettingPrefs.REFRESH_TIME_POSITION, 0);
		}
	}

	@Override
	protected void onDestroy() {
		getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
		super.onDestroy();
	}

}
